<?php
/*
 +----------------------------------------------------------------------
 + Title        : Jwt 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2019/6/14 11:59
 + Last-time    : 2019/6/14 11:59+ 86187
 + Desc         : Jwt
 +----------------------------------------------------------------------
*/


namespace app\common\lib\jwt;


use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;
use think\facade\Cache;
use think\facade\Config;

class Jwt
{
    protected $error;

    /**
     * @return mixed
     */
    public function getError()
    {
        return $this->error;
    }


    public function create(array $user)
    {
        if (!$user) {
            self::setError('uid非法!');
            return false;
        }
        $signer = new Sha256();
        $token = (new Builder())->setIssuer(Config::get('token.issuer'))
                                ->setAudience(Config::get('token.audience'))
                                ->setId(Config::get('token.id'), true)//自定义标识
                                ->setIssuedAt(time())//当前时间
                                ->setExpiration(time() + Config::get('token.expire'))//token有效期时长
                                ->set('user', $user)
                                ->sign($signer, Config::get('token.salt'))
                                ->getToken();
        $token = (string) $token;
        //存入缓存, 做注销操作
        $key = 'token_' . $user['uid'];
        cache($key, $token, Config::get('token.expire') + 60);
        return $token;

    }

    public function validate($token1)
    {
        try {
            $token = (new Parser())->parse((String) $token1);
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }

        $signer = new Sha256();
        if (!$token->verify($signer, Config::get('token.salt'))) {
            $this->error = '数据签名错误!';
            return false; //签名不正确
        }
        $validationData = new ValidationData();
        $validationData->setIssuer(Config::get('token.issuer'));
        $validationData->setAudience(Config::get('token.audience'));
        $validationData->setId(Config::get('token.id'));//自字义标识
        if ($token->validate($validationData) === false) {
            $this->error = '签名数据校验失败!';
            return false;
        } else {
            $user = $token->getClaim('user');
            return $user;
        }
    }
}